﻿using System;
using ControleRepresentante.Logic.Models;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.SqlCommand;

namespace ControleRepresentante.Logic.Repositories.SearchExtensions
{
    public class PedidoJolitexSearchExtension : ISearchExtension
    {
        private readonly string m_CodigoJolitex;
        private readonly bool? m_Sincronizado;
        private readonly bool m_AllJolitex;

        public PedidoJolitexSearchExtension(string codigoJolitex, bool? sincronizado, bool allJolitex)
        {
            m_CodigoJolitex = codigoJolitex;
            m_Sincronizado = sincronizado;
            m_AllJolitex = allJolitex;
        }

        public ICriteria Execute(ICriteria criteria, string tableAlias)
        {
            if (m_Sincronizado.HasValue || !String.IsNullOrWhiteSpace(m_CodigoJolitex))
            {
                DetachedCriteria detachedCriteria = DetachedCriteria.For<PedidoJolitex>()
                    .SetProjection(Projections.Property<PedidoJolitex>(x => x.Id))
                    .Add(Restrictions.EqProperty(tableAlias + ".Id", Projections.Property<PedidoJolitex>(x => x.Id)));
                if (m_Sincronizado.HasValue)
                {
                    detachedCriteria.Add(Restrictions.Eq(Projections.Property<PedidoJolitex>(x => x.Sincronizado), m_Sincronizado.Value));
                }
                if (!String.IsNullOrWhiteSpace(m_CodigoJolitex))
                {
                    detachedCriteria.Add(Restrictions.Eq(Projections.Property<PedidoJolitex>(x => x.Codigo), m_CodigoJolitex));
                }
                criteria = criteria.Add(Subqueries.Exists(detachedCriteria));
            }
            if (m_AllJolitex)
            {
                criteria.CreateCriteria(tableAlias + ".Fabrica", "fab", JoinType.InnerJoin)
                    .CreateCriteria("fab.FabricaJolitex", "fabjol", JoinType.InnerJoin)
                    .Add(Restrictions.Eq(Projections.Property<FabricaJolitex>(x => x.IsJolitex), true));
            }
            return criteria;
        }
    }
}
